package com.lzx.adx.report.controller.v1.xmly;


import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.URLUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONObject;
import com.lzs.adx.commmon.utils.JsonUtils;
import com.lzs.adx.commmon.utils.Result;
import com.lzx.adx.report.bean.mapper.ReportMapper;
import com.lzx.adx.report.cache.AccountLocalCache;
import com.lzx.adx.report.dto.AccountDTO;
import com.lzx.adx.report.dto.ReportDTO;
import com.lzx.adx.report.enums.ElmCovertXmlyEventTypeEnums;
import com.lzx.adx.report.model.xmly.XmlyRequest;
import com.lzx.adx.report.service.ReportService;
import com.lzx.adx.report.util.AdPerUtil;
import com.lzx.adx.report.util.UrlParamsReplacer;
import com.lzx.adx.report.util.UrlUtil;
import com.lzx.adx.report.util.helper.KkHeper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.*;

@RequestMapping("/xmly/kk")
@RestController
@Slf4j
@RequiredArgsConstructor
public class XmlyKkController {

    @Autowired
    private ReportService reportService;

    @Autowired
    private ThreadPoolTaskExecutor reportExecutor;

    @Autowired
    private ReportMapper reportMapper;



    @GetMapping("/report")
    public ResponseEntity report(XmlyRequest reportRequest, HttpServletRequest request) {
        log.info("接收到喜马拉雅到夸克的请求参数为{}", JsonUtils.toJsonString(reportRequest));
        //1.收到监测的数据存储
        ReportDTO reportDTO = reportMapper.toReportDTO(reportRequest);
        reportDTO.setBizRequestId(IdUtil.fastSimpleUUID()+reportDTO.getDspId());
        reportDTO.setCreateTime(new Date());
        reportDTO.setUpdateTime(new Date());
        reportDTO.setExtend(JsonUtils.toJsonString(reportRequest));
        reportDTO.setTraceTime(String.valueOf(System.currentTimeMillis() / 1000));
        reportExecutor.execute(() -> {
            reportService.saveData(reportDTO);
        });

        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportRequest.getDspId());

        String finalUrl = KkHeper.covertUrl(accountDTO, reportRequest, reportDTO);

        log.info("账号为{},完整的西马拉雅-夸克请求地址为{}", reportRequest.getDspId(), finalUrl);
        //2.2调用饿了嘛，上报接口
        String body = HttpUtil.createGet(finalUrl).execute().body();
        log.info("账号为{} 西马拉雅接收了-夸克，上报的接口，响应的结果为{}", reportRequest.getDspId(), body);

        return ResponseEntity.ok(new Result());
    }




    /**
     * 饿了么回传
     * @param requestId 请求参数
     * @return ResponseEntity
     * @throws Exception
     */
    @GetMapping("callback")
    public ResponseEntity callBackUrl(String requestId) throws Exception {
        String eventType="1";
        log.info("西马拉雅接收了夸克回调信息，请求流水号{}",requestId);
        if (StringUtils.isBlank(requestId)){
            log.info("西马拉雅接收了夸克回调信息，请求流水号空,不做回传");
            return ResponseEntity.ok(new Result());
        }
        //1.把转换结果更新到数据库
        Map<String,Object> params=new HashMap<>();
        params.put("bizRequestId",requestId);
        List<ReportDTO> list = reportService.list(params);
        ReportDTO reportDTO;
        if(CollectionUtil.isNotEmpty(list)){
            reportDTO = list.get(0);
            reportDTO.setResultType(eventType);
            reportDTO.setResultTime(String.valueOf(System.currentTimeMillis()));
            reportDTO.setUpdateTime(new Date());
            reportService.updateData(reportDTO,eventType);
        }else{
            log.error("当前流水号，系统当前不存在");
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).build();
        }

        //2.从缓存加载配置
        AccountDTO accountDTO = AccountLocalCache.getInstance().get(reportDTO.getDspId());
        String sspExtend = accountDTO.getSspExtend();
        //如果不为空，且sspExtend
        if(StringUtils.isNotBlank(sspExtend)){
            JSONObject jsonObject = JSONObject.parseObject(sspExtend);
            Double per = jsonObject.getDouble("per");
            if(Objects.nonNull(per)){
                if(!AdPerUtil.randomPer(per)){
                    log.info("流水号为 {} 超出了比例外，本次随机的值为{}，dspId为{}",reportDTO.getBizRequestId(),per,reportDTO.getDspId());
                    return ResponseEntity.ok(new Result());
                }
            }
        }
        //2.从缓存加载配置
        String callback = reportDTO.getCallback();
//        String finalResultUrl = UrlParamsReplacer.replaceTypeParameter(callback, "act");
        log.info("账号为{}请求流水号{}夸克给给喜马拉雅上报回传结果，完整的URl{}",reportDTO.getDspId(),requestId,callback);
        HttpRequest body = HttpUtil.createGet(callback);
        String result = body.execute().body();
        log.info("账号为{}请求流水号{}夸克给给喜马拉雅上报响应结果{}",reportDTO.getDspId(),requestId,result);
        return ResponseEntity.ok(new Result());
    }




}
